<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-input
        placeholder="用户ID"
        v-model="listQuery.uid"
        clearable
      ></el-input>
      <el-date-picker
        v-model="daterangeValue"
        :picker-options="daterangePickerOptions"
        type="daterange"
        :clearable="false"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy/MM/dd"
        @change="onDateChange"
      />
      <el-button type="primary" :loading="listLoading" @click="onSearch"
        >搜索</el-button
      >
      <el-button
        v-loading="exporting"
        :disabled="exporting"
        type="primary"
        size="small"
        icon="el-icon-edit"
        @click="onExport"
        >导出</el-button
      >
    </div>
    <div class="cs-filter-result">
      <AdvanceTable
        :loading="listLoading"
        :columns="columns"
        :list="list"
        :height="'calc(100vh - 200px)'"
        @onSortChange="onSortChange"
      >
        <template slot="用户id" slot-scope="{ row }">
          <TooptipsCom :user-id="row['用户id']" />
        </template>
      </AdvanceTable>
    </div>
  </div>
</template>

<script>
import AdvanceTable from '@/components/AdvanceTable'
import { viewData, exportData, getView, rawQuery } from '@/api/es'
import { parseTime } from '@/utils'

export default {
  name: 'EsViewData',
  components: { AdvanceTable },
  data() {
    const query = this.$route.query
    return {
      id: query && query.id,
      exporting: false,
      list: [],
      listLoading: true,
      columns: [],
      daterangeValue: [],
      listQuery: {},
      requestBody: {},
      requestBodyClone: {},
    }
  },
  created() {
    this.getViewQuery()
    this.doSearch()
  },
  methods: {
    prettyContent(content) {
      var datePattern = new RegExp(/^[\d-]+T[\d-:.]+Z$/) //日期
      if (content == 'NaN') {
        return '-'
      }
      if (datePattern.test(content)) {
        return parseTime(content)
      }
      if (/^\d+.0+$/.test(content)) {
        return parseInt(content)
      }
      if (/^\d+.\d+$/.test(content)) {
        return parseFloat(Number(content).toFixed(2))
      }
      return content
    },
    getViewQuery() {
      getView(this.id).then((resp) => {
        const route = Object.assign({}, this.$route, { title: resp.data.name })
        this.$store.dispatch('tagsView/updateVisitedView', route)
        this.requestBody = resp.data.requestBody
        if (this.requestBody.query) {
          let { query } = this.requestBody
          this.requestBodyClone = JSON.parse(
            JSON.stringify(resp.data.requestBody)
          )
          if (query) {
            let dateRange = this.getQueryDateRange()
            if (dateRange.date) {
              this.daterangeValue = [
                new Date(dateRange.date['gte']),
                new Date(dateRange.date['lte']),
              ]
            }
          }
        }
      })
    },
    doSearch() {
      if (!this.id) {
        this.listLoading = false
        return
      }
      viewData(this.id, {}).then((resp) => {
        this.list = Object.freeze(resp.data.rows)
        resp.data.headers.forEach((item) => {
          let col = {
            key: item,
            label: item,
            visible: true,
            filter: this.prettyContent,
          }
          if (item === '用户id') {
            col.slot = true
          }
          this.columns.push(col)
        })
        this.listLoading = false
      })
    },
    getQueryFilterKeyIndex(key) {
      return this.requestBody.query.bool.filter.findIndex((item) => {
        return item.term && item.term[key]
      })
    },
    getQueryDateRange() {
      let idex = -1
      if (this.requestBody.query.bool) {
        let dateRange = this.requestBody.query.bool.filter.find(
          (item, index) => {
            if (item['range'] && item['range']['date_time']) {
              idex = index
              return item['range'] && item['range']['date_time']
            }
          }
        )
        return {
          index: idex,
          date: (dateRange && dateRange.range.date_time) || null,
        }
      } else {
        return {
          index: this.requestBody.query.range ? 0 : -1,
          date:
            this.requestBody.query.range &&
            this.requestBody.query.range.date_time,
        }
      }
    },
    onSearch(e, sort) {
      this.listLoading = true
      const { query } = this.requestBody
      if (query.bool && query.bool.filter) {
        this.handleRequestBody(sort)
      } else {
        this.requestBody.query = {
          bool: {
            filter: [],
          },
        }
        this.handleRequestBody(sort)
      }
      rawQuery({
        aggs: this.requestBody.aggs,
        query: this.requestBody.query,
        size: 0,
      }).then((resp) => {
        this.list = Object.freeze(resp.data.rows)
        this.listLoading = false
      })
    },
    handleRequestBody(sort) {
      this.handleUidFilter()
      this.handleDateFilter()
      //查询某个用户某个时间段数据
      let keys = Object.keys(this.requestBody.aggs)
      if (
        this.daterangeValue &&
        this.daterangeValue.length &&
        this.listQuery.uid
      ) {
        this.requestBody.aggs[keys[0]].date_histogram = {
          field: 'date_time',
          calendar_interval: '1d',
          order: {
            _key: 'desc',
          },
        }
        delete this.requestBody.aggs[keys[0]]['terms']
        this.replaceColumn(keys[0], '日期', 90)
      } else {
        delete this.requestBody.aggs[keys[0]]['date_histogram']
        this.requestBody.aggs[keys[0]]['terms'] = JSON.parse(
          JSON.stringify(this.requestBodyClone.aggs[keys[0]]['terms'])
        )
        if (sort) {
          this.handleSort(sort)
        }
      }
    },
    replaceColumn(key, label, width) {
      for (var i = 0, len = this.columns.length; i < len; i++) {
        if (this.columns[i]['key'] === key) {
          this.columns[i]['label'] = label
          if (width) {
            this.columns[i]['width'] = `${width}`
          }
        }
      }
    },
    handleUidFilter() {
      let id_index = this.getQueryFilterKeyIndex('user.account_id')
      if (this.listQuery.uid) {
        if (id_index > -1) {
          this.requestBody.query.bool.filter.splice(id_index, 1, {
            term: {
              'user.account_id': this.listQuery.uid,
            },
          })
        } else {
          this.requestBody.query.bool.filter.push({
            term: {
              'user.account_id': this.listQuery.uid || '',
            },
          })
        }
      } else {
        if (id_index > -1) {
          this.requestBody.query.bool.filter.splice(id_index, 1)
        }
      }
    },
    handleDateFilter() {
      let dateRange_index = this.getQueryDateRange().index
      if (this.daterangeValue && this.daterangeValue.length) {
        let start_time = parseTime(this.daterangeValue[0], '{y}-{m}-{d}')
        let end_time = parseTime(this.daterangeValue[1], '{y}-{m}-{d}')
        if (dateRange_index > -1) {
          this.requestBody.query.bool.filter.splice(dateRange_index, 1, {
            range: {
              date_time: {
                gte: start_time,
                lte: end_time,
              },
            },
          })
        } else {
          this.requestBody.query.bool.filter.push({
            range: {
              date_time: {
                gte: start_time,
                lte: end_time,
              },
            },
          })
        }
      } else {
        if (dateRange_index > -1) {
          this.requestBody.query.bool.filter.splice(dateRange_index, 1)
        }
      }
    },
    onDateChange(date) {
      this.daterangeValue = date
    },
    onExport() {
      this.exporting = true
      exportData(this.$route.query.id, {})
        .then((resp) => {
          // this.$router.push(resp.data)
          window.open(resp.data)
          this.exporting = false
        })
        .finally(() => {
          this.exporting = false
        })
    },
    onSortChange(sort) {
      this.onSearch(null, sort)
    },
    handleSort(sort) {
      let { prop, order } = sort
      let aggs = this.requestBody.aggs
      prop = prop.replace(/\./g, '>')
      order = order === 'ascending' ? 'desc' : 'asc'
      const keys = Object.keys(aggs)
      let key = keys[0]
      if (aggs[key].terms) {
        aggs[key].terms.order = {
          [prop]: order,
        }
      }
    },
  },
}
</script>

<style scoped>
</style>
